package com.jushu.storbox.task.tqueue;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;

import com.jushu.storbox.callback.IShareDownloadThumbnailCallback;
import com.jushu.storbox.util.LogUtil;

public class ShareDownloadThumbnailTask implements Runnable {

	private final static String LOG_TAG = "ShareDownloadThumbnailTask";
	private final Context context;
	private final String iconUrl;
	private final String iconPath;
	private IShareDownloadThumbnailCallback callback = null;
	private boolean isSuccess = false;
	
	public ShareDownloadThumbnailTask(Context context, String iconUrl, String iconPath, IShareDownloadThumbnailCallback callback) {
		// TODO Auto-generated constructor stub
		this.context = context;
		this.iconUrl = iconUrl;
		this.iconPath = iconPath;
		if (null == callback) {
			callback = new IShareDownloadThumbnailCallback() {
				
				@Override
				public void onSuccess() {
					// TODO Auto-generated method stub
				}
				
				@Override
				public void onStart() {
					// TODO Auto-generated method stub
				}
				
				@Override
				public void onProgress(int currentProgress, long currentSize, long maxSize) {
					// TODO Auto-generated method stub
				}
				
				@Override
				public void onFailure(Throwable t) {
					// TODO Auto-generated method stub
				}
			};
		}
		this.callback = callback;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		isSuccess = false;
		callback.onStart();// start
		//
		File iFile = new File(iconPath);
		FileOutputStream fos = null;
		int responseCode = -1;
		InputStream in = null;
		
		try {
			URL url = new URL(iconUrl);//"http://192.xx.xx.xx/mypath/img1.jpg
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setDoInput(true);
            con.connect();
            responseCode = con.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) {
            	long maxProgress = con.getContentLength();
                //download 
                in = con.getInputStream();
                fos = new FileOutputStream(iFile);
    			int len = 0;
    			double currentProgress = 0;
    			double progress = 0;
    			double oldProgress = 0;
    			byte[] buff = new byte[512];
    			while ((len = in.read(buff)) != -1) {
    				fos.write(buff, 0, len);
    				currentProgress += len;
    				oldProgress = currentProgress * 100 / maxProgress;
    				if ((int) progress != (int) oldProgress) {
    					progress = oldProgress;
    					callback.onProgress((int) progress, (long) currentProgress,
    							maxProgress);// onProgress
    				}
    			}
    			isSuccess = true;
    			// dbHelper.updateTransStatus(Constant.DOWNLOAD_SUCCESS_UPDATE_DB,
    			// fileID);
            } else {
            	isSuccess = false;
            	Exception e = new Exception("download tumbnail icon fail:connect server fail!");
            	LogUtil.e(LOG_TAG, "[" + iconPath + "]" + e.getLocalizedMessage());
				callback.onFailure(e.fillInStackTrace());// onFail
					// dbHelper.updateTransStatus(Constant.DOWNLOAD_CANCEL_UPDATE_DB,
					// fileID);
            }
		} catch (Exception e) {
			isSuccess = false;
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "[" + iconPath + "]" + e.getLocalizedMessage());
			callback.onFailure(e.fillInStackTrace());// onFail
			// dbHelper.updateTransStatus(Constant.DOWNLOAD_FAIL_UPDATE_DB,
			// fileID);
		} finally {
			try {
				if (null != in) {
					in.close();
				}
				//
				if (null != fos) {
					fos.close();
				}
				if (isSuccess) {
					callback.onSuccess();// onSuccess
				}
			} catch (Exception e) {
				isSuccess = false;
				e.printStackTrace();
				LogUtil.e(LOG_TAG, "[" + iconPath + "]" + e.getLocalizedMessage());
				callback.onFailure(e.fillInStackTrace());// onFail
				// dbHelper.updateTransStatus(Constant.DOWNLOAD_FAIL_UPDATE_DB,
				// fileID);
			}
		}
	}
	
	// callback
	public void setCallback(IShareDownloadThumbnailCallback callback) {
		this.callback = callback;
	}
}
